document.addEventListener('DOMContentLoaded', () => {
    $.ajax({
        url: host + "/api/stock/recommend",
        type: "get",
        success: function (res) {
            console.log(res)
            let arr = res.data
            let resArr = []
            arr.map(item => {
                console.log(item.df.trade_date.slice(-3)[0])
                let param = {
                    name: item.name,
                    code: item.code,
                    closePrice: item.df.close.slice(-4)[0],
                    highPrice: item.df.high.slice(-3)[0],
                    nextTradingDay: item.df.trade_date.slice(-3)[0],
                    lastTradingDay: item.df.trade_date.slice(-4)[0]
                }
                resArr.push(param)
            })
            dealWebData(resArr)//启动填充数据函数

            //给显示的区域绑定鼠标事件
            $("#content").bind("mouseover",function(){StopScroll();});
            $("#content").bind("mouseout",function(){StartScroll();});

            // 初始化计时器
            let timer = setInterval(checkData, 1000);

            // 检查数据的函数
            function checkData() {
                // 假设这是获取数据的函数，这里需要替换为实际的API调用
                const data = resArr;

                if (data) {
                    // 如果数据已经到达，清除计时器并执行特定方法
                    clearInterval(timer);
                    //启动滚动定时器
                    StartScroll();
                }
            }
        }
    })
    // 模拟从接口获取的数据
    // const stockData = [
    //     { name: "Apple Inc.", code: "AAPL", closePrice: 150.00, highPrice: 155.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Microsoft Corp.", code: "MSFT", closePrice: 250.00, highPrice: 260.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Amazon.com Inc.", code: "AMZN", closePrice: 3300.00, highPrice: 3350.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Alphabet Inc.", code: "GOOGL", closePrice: 2800.00, highPrice: 2850.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Meta Platforms Inc.", code: "META", closePrice: 350.00, highPrice: 360.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Tesla Inc.", code: "TSLA", closePrice: 700.00, highPrice: 720.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "NVIDIA Corp.", code: "NVDA", closePrice: 600.00, highPrice: 610.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Netflix Inc.", code: "NFLX", closePrice: 500.00, highPrice: 510.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "Adobe Inc.", code: "ADBE", closePrice: 550.00, highPrice: 560.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
    //     { name: "PayPal Holdings Inc.", code: "PYPL", closePrice: 270.00, highPrice: 280.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" }
    // ];

    function dealWebData(stockData) {
        const container_top = document.getElementById('recommend_top');
        const stockBoxes_top = container_top.getElementsByClassName('stock-box');

        const container_bottom = document.getElementById('recommend_bottom');
        const stockBoxes_bottom = container_bottom.getElementsByClassName('stock-box');

        const container_big = document.getElementById('stockContainer-big');
        const stockBoxes_big = container_big.getElementsByClassName('stock-box');
        // 填充股票数据
        for (let i = 0; i < 10; i++) {
            const stock = stockData[i];
            const stockBox_top = stockBoxes_top[i];
            const stockBox_bottom = stockBoxes_bottom[i];
            const stockBox_big = stockBoxes_big[i];
            const formattedNextTradingDay = formatDate(stock.nextTradingDay);
            const formattedLastTradingDay = formatDate(stock.lastTradingDay);

            stockBox_top.innerHTML = `
            <div class="stock-info">${stock.name} (${stock.code})</div>
            <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
        `;
            stockBox_bottom.innerHTML = `
            <div class="stock-info">${stock.name} (${stock.code})</div>
            <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
        `;
            stockBox_big.innerHTML = `
            <div class="stock-info">${stock.name} (${stock.code})</div>
            <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
        `;
            stockBox_top.onclick = () => {
                const params = new URLSearchParams({
                    name: stock.name,
                    code: stock.code,
                    closePrice: stock.closePrice.toFixed(2),
                    highPrice: stock.highPrice.toFixed(2)
                });
                location.href = `main.html?${params.toString()}`;/*当前页面*/
                // window.open(`main.html?${params.toString()}`, '_blank');/*新页面*/
            };
            stockBox_bottom.onclick = () => {
                const params = new URLSearchParams({
                    name: stock.name,
                    code: stock.code,
                    closePrice: stock.closePrice.toFixed(2),
                    highPrice: stock.highPrice.toFixed(2)
                });
                location.href = `main.html?${params.toString()}`;/*当前页面*/
                // window.open(`main.html?${params.toString()}`, '_blank');/*新页面*/
            };
            stockBox_big.onclick = () => {
                const params = new URLSearchParams({
                    name: stock.name,
                    code: stock.code,
                    closePrice: stock.closePrice.toFixed(2),
                    highPrice: stock.highPrice.toFixed(2)
                });
                location.href = `main.html?${params.toString()}`;/*当前页面*/
                // window.open(`main.html?${params.toString()}`, '_blank');/*新页面*/
            };
        }
    }




    // 格式化日期为 "MM-DD"
    // function formatDate_(dateString) {
    //     const date = new Date(dateString);
    //     const month = (date.getMonth() + 1).toString().padStart(2, '0');
    //     const day = date.getDate().toString().padStart(2, '0');
    //     return `${month}-${day}`;
    // }

    // 后台返回的格式是 20240608 这样的 调用之前的函数会出问题
    function formatDate(dateString) {
        dateString = "" + dateString
        // 提取年份、月份和日期
        let year = parseInt(dateString.substring(0, 4));
        let month = parseInt(dateString.substring(4, 6)) - 1; // 月份从0开始
        let day = parseInt(dateString.substring(6, 8));

        let date = new Date(year, month, day);
        const monthStr = (date.getMonth() + 1).toString().padStart(2, '0');
        const dayStr = date.getDate().toString().padStart(2, '0');
        return `${monthStr}-${dayStr}`;
    }

});

let interval=1500;//两次滚动之间的时间间隔
let stepsize=$(window).height()*0.125;//滚动一次的长度，必须是行高的倍数,这样滚动的时候才不会断行
// console.log($(window).height())
let scrollspeed="slow";//可选("slow", "normal", or "fast")，或者滚动动画时长的毫秒数
let objInterval=null;//上边这些都是滚动的参数
//启动定时器，开始滚动
function StartScroll(){
    objInterval=setInterval("verticalloop()",interval);
}
//清除定时器，停止滚动
function StopScroll(){
    window.clearInterval(objInterval);
}
//控制滚动
function verticalloop(){
//判断是否上部内容全部移出显示区域
//如果是，从新开始;否则，继续向上移动
    if($("#content").scrollTop()>=$("#recommend_top").outerHeight()){
        $("#content").scrollTop($(window).height*0.625+"px");//$("#content").scrollTop()-$("#recommend_top").outerHeight()
    }
//使用jquery创建滚动时的动画效果
    $("#content").animate({"scrollTop" : $("#content").scrollTop()+stepsize +"px"},scrollspeed,function(){
    });
}










